#!/usr/bin/env python3

from pathlib import Path

import gi
gi.require_version('Gtk', '3.0')

# To make this available install Vte with:
#     sudo apt install libvte-2.91-dev
gi.require_version('Vte', '2.91')

from gi.repository import GObject, GLib, Vte, Gtk  # noqa


GObject.type_register(Vte.Terminal)


class KuraTerm(object):

    def __init__(self):
        self._builder = Gtk.Builder()
        self._builder.add_from_file(str(
            Path(__file__).parent / 'kuraterm.glade'
        ))

        # Get objects
        def go(identifier):
            widget = self._builder.get_object(identifier)
            if widget is None:
                raise ValueError('Widget "{}" not found'.format(identifier))

            return widget

        # Get widgets
        self._terminal = go('terminal')
        self._window = go('window')

        # Connect signals
        self._builder.connect_signals(self)

        # Spawn terminal
        self._child_exited_cb(self._terminal, 0)

        # Show app
        self._window.set_default_size(800, 480)
        self._window.show()

    def _child_exited_cb(self, term, status, user_data=None):
        self._terminal.spawn_sync(
            Vte.PtyFlags.DEFAULT,
            None,
            ['/bin/bash'],
            None,
            GLib.SpawnFlags.DEFAULT,
        )

    def start(self):
        Gtk.main()

    def stop(self, widget, event, user_data=None):
        Gtk.main_quit()


if __name__ == '__main__':
    try:
        app = KuraTerm()
        app.start()

    except KeyboardInterrupt:
        pass
